import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: sessionStorage.getItem('token') || '',
    userInfo: JSON.parse(sessionStorage.getItem('userInfo') || 'null')
  }),
  
  getters: {
    isLoggedIn() {
      return !!this.token
    },
    
    // 判断是否是管理员
    isAdmin() {
      return this.userInfo?.role === 'admin'
    }
  },
  
  actions: {
    setToken(token) {
      this.token = token
      sessionStorage.setItem('token', token)
    },
    
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    
    updateUserInfo(updates) {
      this.userInfo = { ...this.userInfo, ...updates }
      sessionStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    
    logout() {
      this.token = ''
      this.userInfo = null
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
    }
  }
})





